const db = require("../common/db/index")

module.exports = {
  // 添加操作日志
  add(admin_id, admin_name, operation_type, operation_desc) {
    return new Promise((resolve, reject) => {
      // 获取日期时间
      const date = new Date()
      const d = date.toLocaleDateString()
      const t = date.toLocaleTimeString()
      const createAt = d + " " + t

      const sql = 'INSERT INTO pre_operation_log (admin_id, admin_name, operation_type, operation_desc, createAt) VALUES (?, ?, ?, ?, ?)';
      db.query(sql, [admin_id, admin_name, operation_type, operation_desc, createAt])
        .then(
          result => {
            resolve({
              code: 200,
              msg: "记录操作日志成功",
              result: result
            })
          },
          err => {
            reject({
              code: 500,
              msg: "记录操作日志失败",
              err: err
            })
          }
        )
    })
  },

  // 获取操作日志列表（支持按用户ID过滤）
  items(page_num, page_size, admin_id = null) {
    return new Promise(async (resolve, reject) => {
      try {
        let countSql = 'SELECT count(*) as total FROM pre_operation_log WHERE 1=1';
        let sql = 'SELECT * FROM pre_operation_log WHERE 1=1';
        let params = [];

        // 如果指定了admin_id，则只查询该用户的操作日志
        if (admin_id !== null) {
          countSql += ' AND admin_id = ?';
          sql += ' AND admin_id = ?';
          params.push(admin_id);
        }

        const rows = await db.query(countSql, params);

        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
        let page_size2 = (parseInt(page_size))
        sql += ` ORDER BY createAt DESC limit ${page_num2} , ${page_size2}`

        await db.query(sql, params)
          .then(
            data => {
              resolve({
                total: rows[0].total,
                data,
                msg: "获取操作日志列表成功",
                code: 200
              })
            },
            err => {
              reject({
                err,
                msg: "获取操作日志列表失败",
                code: 500
              })
            }
          )
      } catch (err) {
        reject({
          err,
          msg: "获取操作日志列表失败",
          code: 500
        })
      }
    })
  },

  // 删除操作日志
  remove(id) {
    return new Promise((resolve, reject) => {
      const sql = 'DELETE FROM pre_operation_log WHERE id = ?';
      db.query(sql, [id])
        .then(
          result => {
            resolve({
              code: 200,
              msg: "删除操作日志成功",
              result
            })
          },
          err => {
            reject({
              code: -1,
              err
            })
          }
        )
    })
  }
}

